#-*-coding:utf-8-*-
# Create your views here.
from models import Follow_up,Next_Follow_Date
from models import Members,Salesperson
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from jsondata import JsonResponse
import time,datetime
"""显示其中一用户的FOLLOW-UP"""
def finfo (request, m_id):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    minfo = Members.objects.get(pk = m_id)
    """操作者为SALES时,先检测此用户是否为他本人添加,如不是弹回登录页"""
    if request.session['level'] != "administrators":
        salesid = minfo.salesperson_id
        if request.session['id'] != salesid:
            return HttpResponseRedirect('/')
    f_object = Follow_up.objects.filter(members__id = m_id).order_by('id')
    return render_to_response('flist.html', {'f_object':f_object, 'username':minfo.name, 'm_id':minfo.id})


"""显示添加页面"""
def add (request, m_id):
    return render_to_response('add_f.html', {'m_id':m_id})

"""添加FOLLOW_UP入库"""
def saveadd (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    new_data = request.POST.copy()
    minfo = Members.objects.get(pk = new_data['m_id'])
    """操作者为SALES时,先检测此用户是否为他本人添加,如不是弹回登录页"""
    if request.session['level'] != "administrators":
        salesid = minfo.salesperson_id
        if request.session['id'] != salesid:
            return HttpResponseRedirect('/')

    if request.method == 'POST':
            if new_data.has_key('id'):
                finfo = Follow_up.objects.get(pk = new_data['id'])
                finfo.status = new_data['status']
                finfo.remarks = new_data['remarks']
                members_id = finfo.members_id
            else:
                finfo = Follow_up(
                status = new_data['status'],
                remarks = new_data['remarks'],
                #已没使用
                members_id = '0',
                )
            finfo.save()
            """更新MEMBERS表"""
            NF = Follow_up.objects.filter(members__id = members_id).order_by('-id')[0]
            member = Members.objects.get(pk = members_id)
            if NF:
                member.status = NF.status
            else:
                member.status = '0'
            member.save()
    return HttpResponseRedirect('/edit_u/%s' % new_data['m_id'])


"""调用修改页"""
def edit (request, f_id):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    finfo = Follow_up.objects.get(pk = f_id)
    minfo = Members.objects.get(pk = finfo.members_id)
    """操作者为SALES时,先检测此用户是否为他本人添加,如不是弹回登录页"""
    if request.session['level'] != "administrators":
        salesid = minfo.salesperson_id
        if request.session['id'] != salesid:
            return HttpResponseRedirect('/')
    return render_to_response('add_f.html', {'m_id':minfo.id, 'finfo':finfo})


"""删除"""
def del_f (request, f_id = ""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    """操作者为SALES时,先检测此用户是否为他本人添加"""
    finfo = Follow_up.objects.get(pk = f_id)
    members_id = finfo.members_id
    minfo = Members.objects.get(pk = members_id)
    if request.session['level'] != "administrators":
        salesid = minfo.salesperson_id
        if request.session['id'] != salesid:
            return HttpResponseRedirect('/')
    Follow_up.objects.filter(pk = f_id).delete()
    NF = Follow_up.objects.filter(members__id = members_id).order_by('-id')
    #member=Members.objects.get(pk=minfo.id)
    if NF:
        NF = NF[0]
        minfo.status = NF.status
    else:
        minfo.status = '0'
    minfo.save()
    return HttpResponseRedirect('/edit_u/%s' % minfo.id)



"""next follow up member list"""
def next_follow_list(request,page='1'):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    today=datetime.date.today()
    nf_list=[]
    sid=request.REQUEST.get('sid','')
    if request.session['level']=='sales':
        try:
            sales_obj=Salesperson.objects.get(pk=request.session['id'])
            nf_list=Next_Follow_Date.objects.filter(member__salesperson=sales_obj,is_removed=0,is_deal=0,follow_date__gte=today).order_by('follow_date')
            nf_list2=Next_Follow_Date.objects.filter(member__salesperson=sales_obj,is_removed=0,is_deal=0,follow_date__lt=today).order_by('-follow_date')
        except:
            pass
    else:
        nf_list = Next_Follow_Date.objects.filter(is_removed=0,follow_date__gte=today,is_deal=0).order_by('follow_date')
        nf_list2 = Next_Follow_Date.objects.filter(is_removed=0,follow_date__lt=today,is_deal=0).order_by('-follow_date')
        if sid:
            try:
                sales_obj=Salesperson.objects.get(pk=int(sid))
                nf_list2=nf_list2.filter(member__salesperson=sales_obj)
            except:
                pass

    return render_to_response('next_follow.html', {'nf_list':nf_list,'nf_list2':nf_list2,'today':today})

"""删除"""
def del_next_follow_list (request, nf_id = ""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    """操作者为SALES时,先检测此用户是否为他本人添加"""
    nf_obj = Next_Follow_Date.objects.get(pk = nf_id)
    if request.session['level'] != "administrators":
        sale_obj = nf_obj.member.salesperson
        if request.session['id'] != sale_obj.id:
            return HttpResponse("You can not delete other sale's record")
    nf_obj.is_removed=1
    nf_obj.save()
    return HttpResponseRedirect('/next_follow_list')

"""新客户也就是没follow up过的客户"""
def get_new_customer (request):
    output={}
    output['ok']=''
    try:
        request.session['id']
    except:
        output['ok']='Login Please'
    if request.POST:
        okstr=""
        try:
            pid=request.session['program']
            #p_obj = Projects.objects.get(pk = pid)
        except:
            pid=0
            #p_obj=Projects()
        if output['ok']=='':
            m_list=[]
            if request.session['level']=='sales':
                mm_list=Members.objects.filter(salesperson__id=request.session['id'],projects__id=pid).order_by('-id')[:100]
                i=0
                
                for mm in mm_list:
                    f_list=Follow_up.objects.filter(members__id=mm.id).order_by('id')
                    #okstr=str(mm.projects.id)
                    
                    if not f_list.count():
                        i+=1
                        #m_list.append(mm)
                        try:
                            if i%8==0:
                                okstr+="<A class=s_end style='color:#000000' href='/edit_u/"+str(mm.id)+"/' target='main-frame'><b>"+mm.name+"</b></a><BR>"
                            else:
                                okstr+="<A style='color:#000000' href='/edit_u/"+str(mm.id)+"/' target='main-frame'><b>"+mm.name+"</b></a>"
                        except:
                            pass
        output['ok']=okstr

    return JsonResponse(output)